<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>文件查看器 - 示例服务器 {{ path }}</title>
  <link rel="stylesheet" href="/static/.Template/files/table.css">
  <link rel="stylesheet" href="/static/.Template/files/common.css">
  <style>
    table img {
      width: 2rem;
      /* 设置图片宽度 */
      height: auto;
      /* 保持图片比例 */
    }
  </style>

  <style>
    .table_foot {
      border: 0;
    }

    .table_foot tr {
      border: 0;
    }

    .table_foot tr:hover {
      background-color: #ffffff00;
    }

    .table_foot td {
      padding: 1rem 0;
    }

    .upload-container {
      display: flex;
      flex-direction: row;
      align-items: center;
      margin-left: 0.5rem;
    }

    .file-input {
      display: none;
      /* 隐藏原生的文件输入 */
      cursor: pointer;
    }

    .upload-button {
      padding: 10px 17px;
      font-size: 16px;
      color: white;
      background-color: #38b0d3;
      border: none;
      border-radius: 5px;
      cursor: pointer;
      transition: background-color 0.3s;
      line-height: 0.8rem;
      margin-right: 0.3rem;

    background-color: #ffffff00;
    color: #38b0d3;
    }

    .upload-button:hover {
      background-color: #287f9a;
      
    background-color: #ffffff00;
    color: #287f9a;
    }

    .progress-bar {
      width: 0%;
      height: 20px;
      background-color: #ddd;
      border-radius: 5px;
      overflow: hidden;
    }

    .progress-bar-fill {
      height: 100%;
      background-color: #007BFF;
      text-align: center;
      line-height: 20px;
      color: white;
      width: 0%;
      transition: width 0.4s ease-in-out;
    }
  </style>

</head>

<body>


  <main>
    <!--
      Add any static information or notices here
    -->

    <h1 class="title"><span class="js-path"></span></h1>
    <table>
      <tr>
        <th></th>
        <th><a href="?C=N;O=D">Name</a></th>
        <th><a href="?C=M;O=A">Last modified</a></th>
        <th><a href="?C=S;O=A">Size</a></th>
        <th><a href="?C=D;O=A">Setting</a></th>
      </tr>
      {% if father_folder != "/" %}

      <tr data-url="{{father_folder}}" onclick="go(this)">
        <td><img src="/static/.Template/files/icons/folder.svg" alt="[DIR]"></td>
        <td><a href="{{father_folder}}"> .. </a></td>
        <td> </td>
        <td> &nbsp; </td>
        <td>&nbsp;</td>
      </tr>
      {% endif %}

      {%- for idata in lists %}

      <tr>
        <td><img src="/static/.Template/files/icons/{{idata.icon}}"></td>
        <td data-url="{{idata.url}}" onclick="go(this)"><a href="{{idata.url}}">{{idata.name}}</a></td>
        <td>{{idata.last_update_time}}</td>
        <td>{{idata.size}}</td>
        <td><button class="upload-button" data-name="{{idata.name}}" onclick="delete_this(this)">删除</button></td>
      </tr>

      {% endfor %}


      <tfoot class="table_foot">
        <td colspan="5">
          <div class="upload-container" id="buttons">
            <input type="file" id="fileInput" class="file-input" onchange="handleFileChange()">
            <button class="upload-button" onclick="create_folder(this)">新建</button>
            <button id="progressButton" class="upload-button"
              onclick="document.getElementById('fileInput').click()">上传</button>
          </div>
          <div>
            <div id="progressBar" class="progress-bar" style="width: 0%;"></div>
          </div>
        </td>
      </tfoot>
    </table>

  </main>

  <footer>
    <a href=""><em>Python Directory Listing</em></a>
  </footer>


  <script src="/static/.Template/jquery-3.7.1.min.js"></script>
  <script src="/static/.Template/Pop/plug-in.js"></script>
  <!-- 路由 -->
  <script>
    function go(params) {

      location.assign(params.dataset.url);
    }
  </script>
  <!-- 上传 -->
  <script>

    function handleFileChange() {
      const file = document.getElementById('fileInput').files[0];
      if (file) {
        uploadFile(file);
      }
    }
    function uploadFile(file) {
      const formData = new FormData();
      formData.append('file', file);
      // 创建进度条填充元素
      const progressButton = document.getElementById('progressButton');
      document.getElementById('buttons').style.display = 'none';
      const progressBar = document.getElementById('progressBar');

      progressBar.style.width = '100%';
      const progressBarFill = document.createElement('div');
      progressBarFill.className = 'progress-bar-fill';
      progressBar.appendChild(progressBarFill);

      const xhr = new XMLHttpRequest();
      xhr.open('POST', '/upload?folder={{ path }}', true);

      xhr.upload.onprogress = function (e) {
        if (e.lengthComputable) {
          const percentComplete = (e.loaded / e.total) * 100;
          progressBarFill.style.width = percentComplete + '%';
        }
      };

      xhr.onload = function () {
        if (xhr.status === 200) {
          
          $.Pro("File uploaded successfully")
          setTimeout(function () {
            location.reload();
          }, 800)

        } else {
          $.Pro('Error uploading file:' + xhr.status);
          location.reload();
        }
      };

      xhr.send(formData);
    }

  </script>
  <!-- 新建文件夹 -->
  <script>
    function create_folder(params) {
      html = '<textarea class="input_name" placeholder="请输入文件名" style="width: 100%;height: 100%;border: 0;outline: 0;color: #333;"></textarea>';
      var callback  = (type) => {

        value = $(".input_name").val()
        $.ajax({
          url: '/mkdir',
          type: 'post',
          data: {
            path: "{{path}}",
            type: type,
            folder: value
          },
          success: function (res) {
            // 只有请求成功（状态码为200）才会执行这个函数
            $.Pro(res.message)
            if (res.code == 200) {
              setTimeout(function () {
                location.reload();
              }, 1000)
            }
          },
          error: function (xhr) {
            // 只有请求不正常（状态码不为200）才会执行
            $.Pro('连接失败')
          },
        });
      }
      $.Pop(html,{
        Btn:{

          yes:{vla:"文件",class:"btn btn-primary",ope:function(){callback('file')},},
          no:{vla:"文件夹",class:"btn btn-primary",ope:function(){callback('folder')},},
          cancel:{vla:"取消",class:"btn btn-primary",ope:function(){},},
      }})
    }
  </script>

  <!-- 删除操作 -->
  <script>
    function delete_this(params) {
      html = '确定要删除吗';
      $.Pop(html, 'confirm', function (e) {
        value = $(".input_name").val()
        $.ajax({
          url: '/delete',
          type: 'post',
          data: {
            path: "{{path}}" + params.dataset.name,
          },
          success: function (res) {
            // 只有请求成功（状态码为200）才会执行这个函数
            $.Pro(res.message)
            if (res.code == 200) {
              setTimeout(function () {
                location.reload();
              }, 1000)
            }
          },
          error: function (xhr) {
            // 只有请求不正常（状态码不为200）才会执行
            $.Pro('连接失败')
          },
        });
      })
    }
  </script>
  <!-- 面包屑 -->
  <script>
    function joinUntil(array, index, separator) {
      var result = [];

      for (var i = 0; i <= index; i++) {
        result.push(array[i]);
      }

      return result.join(separator);
    }

    // Make all the icon links unfocusable with tab
    var iconLinks = document.querySelectorAll('.indexcolicon a');
    Array.prototype.forEach.call(iconLinks, function (link) {
      link.setAttribute('tabindex', '-1');
    });

    var path = document.querySelector('.js-path');
    var pathParts = location.pathname.split('/');

    // Removing empty strings
    for (var i = 0; i < pathParts.length;) {
      if (pathParts[i]) {
        i++;
      } else {
        pathParts.splice(i, 1);
      }
    }

    var pathContents = ['<a href="/">主页</a>', '<a href="/files">文件</a>'];
    Array.prototype.forEach.call(pathParts, function (part, index) {
      pathContents.push('<a href="/' + joinUntil(pathParts, index, '/') + '">' + decodeURI(part) + '</a>');
    });


    delete pathContents[2];
    pathContents = pathContents.filter(item => item !== undefined);

    path.innerHTML = pathContents.join('<span style="padding: 0 5px;color: #ccc;font-size: 0.7rem;display: inline-block;height: 1rem;overflow: hidden;">/</span>');
  </script>

</body>

</html>